package com.tc.zigbee.entity.device.ha;

import com.tc.gateway.device.ha.PressureSensor;
import com.tc.gateway.device.listener.SimpleSensorListener;
import com.tc.util.DataUtil;
import com.tc.zigbee.entity.Endpoint;
import com.tc.zigbee.entity.device.ZigbeeDevice;
import com.tc.zigbee.mt.MtCommand;
import com.tc.zigbee.mt.RequestQueue;
import com.tc.zigbee.mt.ZigbeeManager;
import com.tc.zigbee.mt.request.RequestFactory;
import com.tc.zigbee.zcl.ReportConfig;
import com.tc.zigbee.zcl.ReporterConfigurationRecord;
import com.tc.zigbee.zcl.ZclCommandCreator;
import com.tc.zigbee.zcl.ZclConstants;
import com.tc.zigbee.zcl.command.DataValue;

public class ZigbeePressureSensor extends ZigbeeDevice<SimpleSensorListener> implements PressureSensor{

	public ZigbeePressureSensor(Endpoint endpoint,ZigbeeManager m) {
		super(endpoint,m);
		// TODO Auto-generated constructor stub
	}

	public void action() {
		

	}
	public int getPressure(){
		DataValue dv = this.endpoint.getAttribute(ZclConstants.ZCL_CLUSTER_ID_MS_PRESSURE_MEASUREMENT, (short)0x0000);
		if(dv == null)
			return 0;
		return DataUtil.shortValue(dv.value);
	}

	public void receive() {
		MtCommand mc = RequestFactory.MtBindRequest(
				getEndpoint().getParent().getNwkAddress(), 
				DataUtil.longValue(this.getEndpoint().getParent().getIeeeAddress()), 
				getEndpoint().getEndpointId(), 
				ZclConstants.ZCL_CLUSTER_ID_MS_PRESSURE_MEASUREMENT, 
				DataUtil.longValue(manager.coordinator().getIeeeAddress()), 
				manager.remoteControl.getEndpointId()
				);
		RequestQueue.offer(mc);
		
	}

	public void config() {
		ReportConfig c = new ReportConfig();
		ReporterConfigurationRecord rec= new ReporterConfigurationRecord();
		rec.attribute = 0x0000;
		rec.datatype = ZclConstants.ZCL_DATATYPE_UINT16;
		rec.maxInterval = (short)0xffff;
		rec.minInterval = 0x0000;
		rec.reportableChange = new DataValue(ZclConstants.ZCL_DATATYPE_UINT16,DataUtil.bytesValue((short)12));
		c.getRecords().add(rec);

		byte[] zclcommand = ZclCommandCreator.reportConfig((byte)0, c);
		MtCommand mc = RequestFactory.MtAfDataRequest((byte)2,
				getEndpoint().getParent().getNwkAddress(), 
				//(short)1,
				getEndpoint().getEndpointId(), 
				(byte)manager.remoteControl.getEndpointId(), 
				ZclConstants.ZCL_CLUSTER_ID_MS_PRESSURE_MEASUREMENT, 
				(byte)0, 
				(byte)0, 
				(byte)2, 
				(byte)zclcommand.length, 
				zclcommand
				);
		RequestQueue.offer(mc);
		
	}

	@Override
	public double getMax() {
		// TODO Auto-generated method stub
		return 100;
	}

	@Override
	public double getMin() {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public String getUnit() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public double getValue() {
		// TODO Auto-generated method stub
		return getPressure();
	}



}
